<?php

namespace app\api\controller;

use app\common\controller\Api;

/**
 * CSP工单接口
 */
class Csp extends Api
{
    // 无需登录的接口
    protected $noNeedLogin = ['forwardOrderList'];
    // 无需鉴权的接口
    protected $noNeedRight = ['*'];

    /**
     * 转发工单列表接口（GET请求）
     * 
     * @ApiTitle    (获取工单列表)
     * @ApiSummary  (严格模拟原CURL请求的工单数据)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/csp/forwardOrderList)
     * @ApiHeaders  (name=Authorization, type=string, required=true, description="Bearer Token")
     * @ApiHeaders  (name=T-UAP-APPLICATIONCODE, type=string, required=true, description="应用编码")
     * @ApiParams   (name="pageNum", type="integer", required=true, description="页码", example=1)
     * @ApiParams   (name="pageSize", type="integer", required=true, description="每页数量", example=50)
     * @ApiParams   (name="createDate", type="string", required=false, description="日期范围（JSON字符串）", example='["2025-03-15 00:00:00","2025-04-14 23:59:59"]')
     * @ApiReturnParams   (name="code", type="integer", description="状态码")
     * @ApiReturnParams   (name="msg", type="string", description="返回消息")
     * @ApiReturnParams   (name="data", type="object", description="工单数据")
     * @ApiReturn   ({
        "code": 200,
        "msg": "success",
        "data": {
            "list": [
                {
                    "workNo": "WO20230401001",
                    "logisticsStatus": "30"
                }
            ],
            "total": 100
        }
       })
     */
    public function forwardOrderList()
    {
        // 1. 目标API地址（GET参数通过Query传递）
        $apiUrl = 'https://anapi.annto.com/api-csp-admin/csp/head/forwardOrderList?' . http_build_query([
            'pageNum'  => $this->request->param('pageNum', 1),
            'pageSize' => $this->request->param('pageSize', 50),
        ]);

        // 2. 准备Headers（从原CURL逐项复制）
        $headers = [
            'Accept: application/json, text/plain, */*',
            'Accept-Language: zh-CN,zh;q=0.9',
            'Authorization: Bearer ' . $this->request->header('Authorization', 'eyJhbGci...'),
            'Content-Type: application/json;charset=UTF-8', // 即使GET请求，原接口可能仍需此Header
            'T-UAP-APPLICATIONCODE: ' . $this->request->header('T-UAP-APPLICATIONCODE', 'APP202104220005'),
            'T-UAP-RESOURCECODE: ' . $this->request->header('T-UAP-RESOURCECODE', 'RE1202105150061'),
            'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.6834.83 Safari/537.36'
        ];

        // 3. GET请求无需POST Body，但原CURL的JSON参数需转换为Query参数
        // 例如：createDate/logisticsStatusS 等复杂参数需特殊处理
        $extraParams = [
            'createDate' => $this->request->param('createDate', '["2025-03-15 00:00:00","2025-04-14 23:59:59"]'),
            'logisticsStatusS' => $this->request->param('logisticsStatusS', '["30","50","55","60","70","75"]')
        ];
        $apiUrl .= '&' . http_build_query($extraParams);

        // 4. 发送GET请求
        $response = $this->sendGetRequest($apiUrl, $headers);
        $result = json_decode($response, true);

        // 5. 返回标准化响应
        if (isset($result['code']) && $result['code'] == 200) {
            $this->success('success', $result['data']);
        } else {
            $this->error($result['msg'] ?? 'API请求失败');
        }
    }

    /**
     * 发送GET请求（私有方法）
     */
    private function sendGetRequest($url, $headers)
    {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_TIMEOUT => 10
        ]);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
}